<script lang="ts" setup>
import { computed, ref } from 'vue';
import type { FieldRule, FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useI18n } from 'vue-i18n';
import type { ResponseData } from './use';

const props = defineProps<{ id: number }>();
const loading = ref(false);

const formData = ref<ResponseData>({
  content: '',
  contentCategory: '',
  contentType: '',
  displayStatus: 0,
  id: 0,
  link: '',
  name: '',
  pic: '',
  communityId: 0,
  position: 0,
  createName: null,
  createTime: null,
  updateName: null,
  updateTime: null,
});
const formRef = ref<FormInstance>();
const { success } = useNotification();
const { t } = useI18n();

const refresh = async () => {
  const { isSuccess, data } = await $fetch('/admin/suspend/detail/' + props.id, {
    method: 'get',
    loadingStatus: loading,
  });

  if (isSuccess) {
    formData.value = data as ResponseData;
  }
}

const contentsRules = computed<FieldRule[]>(() => {
  switch (formData.value?.contentCategory) {
    case 'email':
      return [
        { type: 'email', message: t('settings.form.validation.email') },
        { required: true, message: t('settings.notification.required') },
      ];
    case 'feedback':
      return [];
    default:
      return [{ required: true, message: t('settings.notification.required') }];
  }
});

const linkRules = computed<FieldRule[]>(() => {
  switch (formData.value?.contentCategory) {
    case 'feedback':
      return [{ type: 'url', required: true }];
    default:
      return [];
  }
});

const dialogClickButton = async (button: string) => {
  if (button !== 'ok') {
    return;
  }

  const res = await formRef.value?.validate();

  if (res) {
    return false;
  }

  const { isSuccess } = await $fetch('/admin/suspend/update', {
    method: 'post',
    data: formData.value,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
  }

  return isSuccess;
}

defineExpose({
  dialogClickButton,
});

refresh();
</script>

<template>
  <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData">
    <AFormItem field="content" :label="$t('settings.view.floatNavigation.index.column3')" :rules="contentsRules">
      <AInput v-if="formData?.contentType === 'text'" v-model="formData.content" allow-clear show-word-limit />
      <OpenUpload v-model="formData.content" v-else-if="formData?.contentType === 'image'" />
    </AFormItem>
    <AFormItem field="link" :label="$t('settings.view.floatNavigation.index.column4')" :rules="linkRules">
      <AInput v-model="formData.link" allow-clear />
    </AFormItem>
  </AForm>
</template>

<style lang="scss" scoped>
</style>
